package com.design.adnroid.campussecondarytrading.activity;

import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.design.adnroid.campussecondarytrading.AppContext;
import com.design.adnroid.campussecondarytrading.adapter.GoodsItemAdapter;
import com.design.adnroid.campussecondarytrading.adapter.ImagePaperAdapter;
import com.design.adnroid.campussecondarytrading.database.DBOperate;
import com.design.adnroid.campussecondarytrading.entity.Goods;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class HomePageActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private ListView listView;
    private ArrayList<Goods> arrayList;
    private ArrayAdapter<Goods> adapter;

    private DBOperate dbOperate;
    //    用于存放小圆点图片
    private List<ImageView> dotViewList;

    //    用于存放轮播效果图片
    private List<ImageView> list;
    private LinearLayout dotLayout;

    private RelativeLayout relativeLayout;
    private int currentItem = 0;//当前页面

    boolean isAutoPlay = true;//是否自动轮播

    private ScheduledExecutorService scheduledExecutorService;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 100) {
                viewPager.setCurrentItem(currentItem);
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        setTitle(getString(R.string.title_activity_homePage));

        dbOperate = new DBOperate(this);
        isAutoPlay = AppContext.isViewPagerIsAutoPlay();

        //        初始化ListView
        initListView();
        //        初始化ViewPager
        initViewPager();

        //        自动轮播
        if (isAutoPlay) {
            startPlay();
        }

        relativeLayout = findViewById(R.id.homePage_layout);
        relativeLayout.setVisibility(AppContext.getRelativeLayoutVisibility());

        ImageView imageView = findViewById(R.id.homePage_close);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scheduledExecutorService.shutdownNow();
                relativeLayout.setVisibility(View.GONE);
                AppContext.setRelativeLayoutVisibility(View.GONE);
            }
        });

    }//onCreat

    public void initListView() {

        listView = findViewById(R.id.homePage_listView);
        arrayList = new ArrayList<>();
        adapter = new GoodsItemAdapter(this, arrayList);
        listView.setAdapter(adapter);

        dbOperate.openDB();
        SQLiteDatabase db = dbOperate.getDb();
        Cursor cursor = db.query(dbOperate.getGoodsTableName(),
                null, "goodsState=0", null,
                null, null, "goodsTime DESC");

        arrayList.clear();
        if (cursor.getCount() != 0) {
            cursor.moveToFirst();
            do {
                byte[] bytes = cursor.getBlob(cursor.getColumnIndex("goodsImage"));
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, null);

                Goods goods = new Goods();
                goods.setGoodsId(cursor.getString(cursor.getColumnIndex("goodsId")));
                goods.setGoodsName(cursor.getString(cursor.getColumnIndex("goodsName")));
                goods.setGoodsText(cursor.getString(cursor.getColumnIndex("goodsText")));
                goods.setGoodsImage(bitmap);
                goods.setGoodsTime(cursor.getString(cursor.getColumnIndex("goodsTime")));
                goods.setGoodsPrice(cursor.getDouble(cursor.getColumnIndex("goodsPrice")));
                goods.setGoodsOwner(cursor.getString(cursor.getColumnIndex("goodsOwner")));
                goods.setGoodsOwnerContact(cursor.getString(cursor.getColumnIndex("goodsOwnerContact")));
                goods.setGoodsState(cursor.getInt(cursor.getColumnIndex("goodsState")));
                goods.setGoodsBuyers(cursor.getString(cursor.getColumnIndex("goodsBuyers")));

                arrayList.add(goods);
                adapter.notifyDataSetChanged();//刷新数据
            } while (cursor.moveToNext());//while

        }//if
        dbOperate.closeDb();
        cursor.close();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String intentGoodsId = (arrayList.get(position)).getGoodsId();
                Intent intent = new Intent(HomePageActivity.this, GoodsActivity.class);
                intent.putExtra("intentGoodsId", intentGoodsId);
                startActivity(intent);
            }
        });

    }

    public void initViewPager() {
        viewPager = findViewById(R.id.homePage_viewPager);
        dotLayout = findViewById(R.id.homePage_dotLayout);
        dotLayout.removeAllViews();
        dotViewList = new ArrayList<>();
        list = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            ImageView dotView = new ImageView(HomePageActivity.this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(
                    LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));

            params.leftMargin = 15;//设置小圆点的外边距
            params.rightMargin = 15;
            params.height = 40;//设置小圆点的大小
            params.width = 40;

            if (i == 0) {
                dotView.setBackgroundResource(R.drawable.point_pressed);
            } else {
                dotView.setBackgroundResource(R.drawable.point_unpressed);
            }
            dotLayout.addView(dotView, params);
            dotViewList.add(dotView);
        }//上面是动态添加了四个小圆点

        ImageView[] imageView = new ImageView[4];
        int[] resid = new int[]{R.drawable.main_img1, R.drawable.main_img2,
                R.drawable.main_img3, R.drawable.main_img4};

        for (int i = 0; i < 4; i++) {
            imageView[i] = LayoutInflater.from(HomePageActivity.this)
                    .inflate(R.layout.viewpager_item, null)
                    .findViewById(R.id.viewPager_item);
            imageView[i].setBackgroundResource(resid[i]);
            list.add(imageView[i]);

        }//上面是动态添加了四个滚动图片

        ImagePaperAdapter adapter = new ImagePaperAdapter(list);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);

        viewPager.addOnPageChangeListener(new MyPageChangeListener());
    }//initView()

    /**
     * 开始轮播图切换
     */
    private void startPlay() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4, TimeUnit.SECONDS);
        //根据他的参数说明，第一个参数是执行的任务，第二个参数是第一次执行的间隔，第三个参数是执行任务的周期；
    }

    /**
     * 执行轮播图切换任务
     */
    private class SlideShowTask implements Runnable {

        @Override
        public void run() {
            synchronized (viewPager) {
                currentItem = (currentItem + 1) % list.size();
                handler.sendEmptyMessage(100);
            }
        }
    }

    /**
     * ViewPager的监听器
     * 当ViewPager中页面的状态发生改变时调用
     */
    private class MyPageChangeListener implements ViewPager.OnPageChangeListener {

        boolean isAutoPlay = false;

        @Override
        public void onPageScrollStateChanged(int arg0) {
            switch (arg0) {
                case 1:// 手势滑动，空闲中
                    isAutoPlay = false;
                    System.out.println(" 手势滑动，空闲中");
                    break;
                case 2:// 界面切换中
                    isAutoPlay = true;
                    System.out.println(" 界面切换中");
                    break;
                case 0:// 滑动结束，即切换完毕或者加载完毕
                    // 当前为最后一张，此时从右向左滑，则切换到第一张
                    if (viewPager.getCurrentItem() == viewPager.getAdapter().getCount() - 1 && !isAutoPlay) {
                        viewPager.setCurrentItem(0);
                        System.out.println(" 滑动到最后一张");
                    }
                    // 当前为第一张，此时从左向右滑，则切换到最后一张
                    else if (viewPager.getCurrentItem() == 0 && !isAutoPlay) {
                        viewPager.setCurrentItem(viewPager.getAdapter().getCount() - 1);
                        System.out.println(" 滑动到第一张");
                    }
                    break;
                default:
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int pos) {
            //这里面动态改变小圆点的被背景，来实现效果
            currentItem = pos;
            for (int i = 0; i < dotViewList.size(); i++) {
                if (i == pos) {
                    (dotViewList.get(pos)).setBackgroundResource(R.drawable.point_pressed);
                } else {
                    (dotViewList.get(i)).setBackgroundResource(R.drawable.point_unpressed);
                }
            }
        }

    }//private class
}
